﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using DormMS.Model.Enum;
using DormMS.Model.ViewModels.Report;

namespace Infrastructure.Tool
{
    public class ExcelTool
    {
        public static void ExportExcel(ReportType reportType, DataTable dt, string fileName = "")
        {
            //生成Excel
            IWorkbook book = BuildWorkbook(reportType, dt);
            //web 下载
            if (fileName == "")
                fileName = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now);
            fileName = fileName.Trim();
            string ext = Path.GetExtension(fileName);

            if (ext.ToLower() == ".xls" || ext.ToLower() == ".xlsx")
                fileName = fileName.Replace(ext, string.Empty);

            HttpResponse httpResponse = System.Web.HttpContext.Current.Response;
            httpResponse.Clear();
            httpResponse.Buffer = true;
            httpResponse.Charset = Encoding.UTF8.BodyName;
            httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            httpResponse.ContentEncoding = Encoding.UTF8;
            httpResponse.ContentType = "application/vnd.ms-excel; charset=UTF-8";
            book.Write(httpResponse.OutputStream);
            httpResponse.End();
        }
        //65536判断处理
        public static HSSFWorkbook BuildWorkbook(ReportType reportType, DataTable dt)
        {
            PropertyInfo[] peroperties = null;
            if (reportType == ReportType.订单表)
            {
                peroperties = typeof(Report_Order).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            else if (reportType == ReportType.发货单)
            {
                peroperties = typeof(Report_DeliverGoods).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            else if (reportType == ReportType.退货单)
            {
                peroperties = typeof(Report_ReturnGoods).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            else if (reportType == ReportType.商品表)
            {
                peroperties = typeof(Report_Product).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            else if (reportType == ReportType.会员)
            {
                peroperties = typeof(Report_Member).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
            //工作簿
            var book = new HSSFWorkbook();
            //工作单元
            ISheet sheet = book.CreateSheet();
            //标题行
            IRow row = sheet.CreateRow(0);
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                ICell cell = row.CreateCell(j, CellType.String);
                cell.SetCellValue(GetDescription(peroperties, dt.Columns[j].ColumnName));
            }
            //
            int rowIndex = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (rowIndex == 50000)
                {
                    sheet = book.CreateSheet(); //创建新单元
                    row = sheet.CreateRow(0); //创建标题
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        ICell cell = row.CreateCell(j, CellType.String);
                        cell.SetCellValue(GetDescription(peroperties, dt.Columns[j].ColumnName));
                    }
                    rowIndex = 0;
                }
                row = sheet.CreateRow(rowIndex + 1); //从第二行开始
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i, CellType.String);
                    cell.SetCellValue(dr[dt.Columns[i].ColumnName].ToString());
                }
                rowIndex++;
            }
            //自动列宽
            for (int i = 0; i < book.Count; i++)
            {
                for (int j = 0; j <= dt.Columns.Count; j++)
                {
                    book[i].AutoSizeColumn(j, true);
                }
            }
            return book;
        }

        public static string GetDescription(PropertyInfo[] peroperties, string field)
        {
            string description = "";
            foreach (PropertyInfo property in peroperties)
            {
                object[] objs = property.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objs.Length > 0)
                {
                    if (property.Name == field)
                    {
                        description = ((DescriptionAttribute)objs[0]).Description;
                        break;
                    }
                }
                else
                {
                    description = field;
                }
            }
            return description;
        }
    }
}
